package org.grow.leave.config;

import org.grow.leave.service.LeaveAccessDecisionManager;
import org.grow.leave.service.LeavePermissionData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

/**
 * @Author: xwg
 * @CreateDate: 2021/10/20
 */
@EnableRedisHttpSession
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private LeavePermissionData leavePermissionData;
    @Autowired
    private LeaveAccessDecisionManager leaveAccessDecisionManager;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().disable();
        http.httpBasic().disable();
        http.csrf().disable();
        http.logout().disable();
//        SecurityFilterIntercepter;
//        FilterSecurityInterceptor
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
//                        进一步 配置FilterSecurityInterceptor
                        o.setSecurityMetadataSource(leavePermissionData);
                        o.setAccessDecisionManager(leaveAccessDecisionManager);
                        return o;
                    }
                }).anyRequest().authenticated();
        http.exceptionHandling()
                .accessDeniedHandler((req, res, e) -> {
                    res.setStatus(820);
                    res.getWriter().println(e.getMessage());
                });
    }
}
